Imports System.Web.UI.WebControls
Imports System.Text.RegularExpressions
Imports System.Text
Imports System.IO
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System
Imports System.Data

Public Class ExImage

#Region " Utility Methods "

    Private Shared Sub CheckFileExists(ByVal sFileName As String)
        If System.IO.File.Exists(sFileName) = True Then
            System.IO.File.Delete(sFileName)
        End If
    End Sub

    Private Function GetEmptyImage(ByVal CurImg As String) As String
        If String.IsNullOrEmpty(CurImg) Then
            Return "spacer.gif"
        Else
            Return CurImg
        End If
    End Function

    Private Function StoreImageExtracted(ByRef sFileName As String) As String
        If sFileName.Length >= 49 Then
            If Path.GetExtension(sFileName) = ".jpg" Then
                sFileName = sFileName.Substring(0, 45) & ".jpg"
            Else
                sFileName = sFileName.Substring(0, 45) & ".gif"
            End If
        End If

        Return sFileName

    End Function

    Private Shared Sub CheckDirectory(ByVal sPath As String)
        If System.IO.Directory.Exists(sPath) = False Then
            System.IO.Directory.CreateDirectory(sPath)
        End If
    End Sub

#End Region

#Region " StoreImage "

    Public Function StoreImage(ByVal DestinationPath As String, ByVal DestinationFileName As String, _
                    ByVal ImageFileStream As Stream, ByVal ImageWidth As Integer, _
                    ByVal CurrentHeight As Integer, ByVal CurrentImageFileName As String) As String

        If String.IsNullOrEmpty(DestinationFileName) = False Then

            DestinationFileName = Path.GetFileName(DestinationFileName).Replace("#", "").Replace(" ", "-")
            DestinationFileName = Path.Combine(DestinationPath, StoreImageExtracted(DestinationFileName))
            CheckFileExists(DestinationFileName)

            MakeThumbnail(ImageFileStream, DestinationFileName, ImageWidth, CurrentHeight, _
                Drawing.Drawing2D.InterpolationMode.HighQualityBicubic)

            Return Path.GetFileName(DestinationFileName)

        Else
            Return String.Empty
        End If

    End Function

    Public Function StoreImage(ByVal sPath As String, ByVal sFileName As String, _
        ByVal ImgFile As String, ByVal EleWidth As Integer, ByVal EleHeight As Integer) As String
        Return StoreImage(sPath, sFileName, ImgFile, EleWidth, EleHeight, "")
    End Function

    Public Function StoreImage(ByVal DestinationPath As String, ByVal DestinationFileName As String, _
    ByVal ImageFileName As String, ByVal ImageWidth As Integer, _
    ByVal ImageHeight As Integer, ByVal CurrentImageFileName As String) As String
        Return StoreImage(DestinationPath, DestinationFileName, ImageFileName, ImageWidth, _
            ImageHeight, CurrentImageFileName, 100)
    End Function

    Public Function StoreImage(ByVal DestinationPath As String, ByVal DestinationFileName As String, _
        ByVal ImageFileName As String, ByVal ImageWidth As Integer, _
        ByVal ImageHeight As Integer, ByVal CurrentImageFileName As String, ByVal ImageQuality As Integer) As String

        If String.IsNullOrEmpty(DestinationFileName) = False Then

            DestinationFileName = Path.GetFileName(DestinationFileName).Replace("#", "")
            DestinationFileName = Path.Combine(DestinationPath, StoreImageExtracted(DestinationFileName))
            CheckFileExists(DestinationFileName)

            MakeThumbnail(ImageFileName, DestinationFileName, ImageWidth, ImageHeight, _
                Drawing.Drawing2D.InterpolationMode.HighQualityBicubic, ImageQuality)

            Return Path.GetFileName(DestinationFileName)

        End If

        Return String.Empty

    End Function

    Public Function StoreImage(ByVal sPath As String, ByVal sFileName As String, _
        ByVal ImgFile As System.Web.UI.HtmlControls.HtmlInputFile, _
        ByVal EleWidth As Integer, ByVal EleHeight As Integer) As String
        Return StoreImage(sPath, sFileName, ImgFile, EleWidth, EleHeight, String.Empty)
    End Function

    '''-----------------------------------------------------------------------------
    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="sPath"></param>
    ''' <param name="sFileName"></param>
    ''' <param name="ImgFile"></param>
    ''' <param name="EleWidth"></param>
    ''' <param name="EleHeight"></param>
    ''' <param name="CurImg"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    ''' <history>
    ''' 	[wcwilson] 	7/8/2003	Created
    ''' </history>
    '''-----------------------------------------------------------------------------
    Public Function StoreImage(ByVal sPath As String, ByVal sFileName As String, _
        ByVal ImgFile As System.Web.UI.HtmlControls.HtmlInputFile, _
        ByVal EleWidth As Integer, _
        ByVal EleHeight As Integer, ByVal CurImg As String) As String

        Dim mFileLength As Integer = ImgFile.PostedFile.ContentLength

        If mFileLength > 0 Then
            Return StoreImage(sPath, sFileName, ImgFile.PostedFile.InputStream, _
                EleWidth, EleHeight, CurImg)
        Else
            Return GetEmptyImage(CurImg)
        End If

    End Function

    Public Function StoreImage(ByVal sPath As String, ByVal sFileName As String, _
    ByVal ImgFile As FileUpload, ByVal EleWidth As Integer, ByVal EleHeight As Integer) As String
        Return StoreImage(sPath, sFileName, ImgFile, EleWidth, EleHeight, String.Empty)
    End Function

    Public Function StoreImage(ByVal sPath As String, ByVal sFileName As String, _
        ByVal ImgFile As FileUpload, ByVal EleWidth As Integer, _
        ByVal EleHeight As Integer, ByVal CurImg As String) As String

        If ImgFile.HasFile Then
            Return StoreImage(sPath, sFileName, ImgFile.PostedFile.InputStream, _
                EleWidth, EleHeight, CurImg)
        Else
            Return GetEmptyImage(CurImg)
        End If

    End Function

    Public Function StoreImage(ByVal sPath As String, _
        ByVal ImgFile As System.Web.UI.HtmlControls.HtmlInputFile, _
        ByVal EleWidth As Integer, ByVal EleHeight As Integer) As String
        Return StoreImage(sPath, ImgFile, EleWidth, EleHeight, String.Empty)
    End Function

    '''-----------------------------------------------------------------------------
    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="sPath"></param>
    ''' <param name="ImgFile"></param>
    ''' <param name="EleWidth"></param>
    ''' <param name="EleHeight"></param>
    ''' <param name="CurImg"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    ''' <history>
    ''' 	[wcwilson] 	6/9/2003	Created
    ''' </history>
    '''-----------------------------------------------------------------------------
    Public Function StoreImage(ByVal sPath As String, _
        ByVal ImgFile As System.Web.UI.HtmlControls.HtmlInputFile, _
        ByVal EleWidth As Integer, ByVal EleHeight As Integer, ByVal CurImg As String) As String

        Return StoreImage(sPath, Clean(ImgFile.PostedFile.FileName), ImgFile, _
            EleWidth, EleHeight, CurImg)

    End Function

#End Region

#Region " Make Thumbnail "

    '''-----------------------------------------------------------------------------
    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="Buffer"></param>
    ''' <param name="sDestination"></param>
    ''' <param name="MaxWidth"></param>
    ''' <param name="MaxHeight"></param>
    ''' <param name="nMode"></param>
    ''' <param name="iJPGQuality"></param>
    ''' <remarks></remarks>
    ''' <history>
    ''' 	[wcwilson] 	6/9/2003	Created
    ''' </history>
    '''-----------------------------------------------------------------------------
    Public Sub MakeThumbnail(ByRef Buffer As Stream, _
                        ByVal sDestination As String, _
                        ByRef MaxWidth As Integer, ByRef MaxHeight As Integer, _
                        ByVal nMode As Drawing2D.InterpolationMode, _
                        Optional ByVal iJPGQuality As Integer = 100)

        Dim iWidth As Integer
        Dim iHeight As Integer
        Dim objImage As System.Drawing.Image
        Dim objBitmap As Bitmap
        Dim objGraphics As Graphics
        Dim objEncoder As Imaging.EncoderParameters

        '     Try
        ' Open the source image
        objImage = New Bitmap(Buffer)

        'get image original width and height 
        Dim intOldWidth As Integer = objImage.Width
        Dim intOldHeight As Integer = objImage.Height
        Dim dblCoef As Double

        'If intMaxSide > MaxSideSize Then
        If intOldWidth > MaxWidth Then
            iWidth = MaxWidth

            dblCoef = MaxWidth / CDbl(intOldWidth)

            If MaxHeight <= Convert.ToInt32((dblCoef * intOldHeight)) Then
                iHeight = MaxHeight
                dblCoef = MaxHeight / CDbl(intOldHeight)
                iWidth = Convert.ToInt32((dblCoef * intOldWidth))
            Else
                iHeight = Convert.ToInt32((dblCoef * intOldHeight))
            End If

        ElseIf intOldHeight > MaxHeight Then
            iHeight = MaxHeight
            dblCoef = MaxHeight / CDbl(intOldHeight)
            iWidth = Convert.ToInt32((dblCoef * intOldWidth))
        Else
            iWidth = intOldWidth
            iHeight = intOldHeight
        End If

        ' Create a new bitmap object with the thumbnail's dimensions
        objBitmap = New Bitmap(iWidth, iHeight)

        ' Create a graphics object, used for resizing
        objGraphics = Graphics.FromImage(objBitmap)

        ' Set the graphics object's InterpolationMode
        objGraphics.InterpolationMode = nMode

        ' Draw the actual thumbnail
        objGraphics.DrawImage(objImage, 0, 0, iWidth, iHeight)

        ' Now, create a new Imaging Encoder...
        objEncoder = New Imaging.EncoderParameters(1)

        ' Tell it to be "Encoder.Quality" with the desired iJPGQuality
        objEncoder.Param(0) = New Imaging.EncoderParameter(Imaging.Encoder.Quality, iJPGQuality)

        ' Using function GetEncoderInfo, write the thumbnail to disc
        sDestination = sDestination.ToLower

        If Path.GetExtension(sDestination) = ".gif" Then
            objBitmap.Save(sDestination, GetEncoderInfo("image/gif"), objEncoder)
        ElseIf Path.GetExtension(sDestination) = ".jpg" Then
            objBitmap.Save(sDestination, GetEncoderInfo("image/jpeg"), objEncoder)
        End If

        Buffer.Close()

    End Sub

    Public Sub MakeThumbnail(ByRef sSource As String, _
                    ByVal sDestination As String, _
                    ByRef MaxWidth As Integer, ByRef MaxHeight As Integer, _
                    ByVal nMode As Drawing2D.InterpolationMode, _
                    Optional ByVal iJPGQuality As Integer = 100)

        Dim iWidth As Integer
        Dim iHeight As Integer
        Dim objImage As System.Drawing.Image
        Dim objBitmap As Bitmap
        Dim objGraphics As Graphics
        Dim objEncoder As Imaging.EncoderParameters

        '      Try
        ' Open the source image
        objImage = New Bitmap(sSource)

        'get image original width and height 
        Dim intOldWidth As Integer = objImage.Width
        Dim intOldHeight As Integer = objImage.Height
        Dim dblCoef As Double

        'If intMaxSide > MaxSideSize Then
        If intOldWidth > MaxWidth Then
            iWidth = MaxWidth

            dblCoef = MaxWidth / CDbl(intOldWidth)

            If MaxHeight <= Convert.ToInt32((dblCoef * intOldHeight)) Then
                iHeight = MaxHeight
                dblCoef = MaxHeight / CDbl(intOldHeight)
                iWidth = Convert.ToInt32((dblCoef * intOldWidth))
            Else
                iHeight = Convert.ToInt32((dblCoef * intOldHeight))
            End If

        ElseIf intOldHeight > MaxHeight Then
            iHeight = MaxHeight
            dblCoef = MaxHeight / CDbl(intOldHeight)
            iWidth = Convert.ToInt32((dblCoef * intOldWidth))
        Else
            iWidth = intOldWidth
            iHeight = intOldHeight
        End If

        ' Create a new bitmap object with the thumbnail's dimensions
        objBitmap = New Bitmap(iWidth, iHeight)

        ' Create a graphics object, used for resizing
        objGraphics = Graphics.FromImage(objBitmap)

        ' Set the graphics object's InterpolationMode
        objGraphics.InterpolationMode = nMode

        ' Draw the actual thumbnail
        objGraphics.DrawImage(objImage, 0, 0, iWidth, iHeight)

        ' Now, create a new Imaging Encoder...
        objEncoder = New Imaging.EncoderParameters(1)

        ' Tell it to be "Encoder.Quality" with the desired iJPGQuality
        objEncoder.Param(0) = New Imaging.EncoderParameter(Imaging.Encoder.Quality, iJPGQuality)

        ' Using function GetEncoderInfo, write the thumbnail to disc
        sDestination = sDestination.ToLower

        If Path.GetExtension(sDestination) = ".gif" Then
            objBitmap.Save(sDestination, GetEncoderInfo("image/gif"), objEncoder)
        ElseIf Path.GetExtension(sDestination) = ".jpg" Then
            objBitmap.Save(sDestination, GetEncoderInfo("image/jpeg"), objEncoder)
        End If

        objBitmap.Dispose()
        objImage.Dispose()

    End Sub

#End Region

#Region " Image Helpers "

    '''-----------------------------------------------------------------------------
    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="mimeType"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    ''' <history>
    ''' 	[wcwilson] 	6/9/2003	Created
    ''' </history>
    '''-----------------------------------------------------------------------------
    Private Function GetEncoderInfo(ByVal mimeType As String) As ImageCodecInfo
        Dim j As Integer
        Dim encoders As ImageCodecInfo()
        encoders = ImageCodecInfo.GetImageEncoders()
        For j = 0 To encoders.Length
            If encoders(j).MimeType = mimeType Then
                Return encoders(j)
            End If
        Next j
        Return Nothing
    End Function

    '''-----------------------------------------------------------------------------
    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="ImageSavePath"></param>
    ''' <param name="MaxWidth"></param>
    ''' <param name="MaxHeight"></param>
    ''' <param name="Buffer"></param>
    ''' <remarks></remarks>
    ''' <history>
    ''' 	[wcwilson] 	6/9/2003	Created
    ''' </history>
    '''-----------------------------------------------------------------------------
    Public Sub ResizeFromStream(ByRef ImageSavePath As String, _
        ByRef MaxWidth As Integer, ByRef MaxHeight As Integer, _
        ByRef Buffer As Stream)

        Dim iWidth As Integer
        Dim iHeight As Integer
        Dim imgInput As System.Drawing.Image = System.Drawing.Image.FromStream(Buffer)

        'Determine image format 
        Dim fmtImageFormat As ImageFormat = imgInput.RawFormat

        'get image original width and height 
        Dim intOldWidth As Integer = imgInput.Width
        Dim intOldHeight As Integer = imgInput.Height
        Dim dblCoef As Double

        'If intMaxSide > MaxSideSize Then
        If intOldWidth > MaxWidth Then
            iWidth = MaxWidth

            dblCoef = MaxWidth / CDbl(intOldWidth)

            If MaxHeight <= Convert.ToInt32((dblCoef * intOldHeight)) Then
                iHeight = MaxHeight
                dblCoef = MaxHeight / CDbl(intOldHeight)
                iWidth = Convert.ToInt32((dblCoef * intOldWidth))
            Else
                iHeight = Convert.ToInt32((dblCoef * intOldHeight))
            End If

        ElseIf intOldHeight > MaxHeight Then
            iHeight = MaxHeight
            dblCoef = MaxHeight / CDbl(intOldHeight)
            iWidth = Convert.ToInt32((dblCoef * intOldWidth))
        Else
            iWidth = intOldWidth
            iHeight = intOldHeight
        End If

        'create new bitmap 
        Dim bmpResized As New Bitmap(imgInput, iWidth, iHeight)

        'save bitmap to disk 
        bmpResized.Save(ImageSavePath, fmtImageFormat)

        'release used resources 
        imgInput.Dispose()
        bmpResized.Dispose()
        '  Buffer.Close()
    End Sub 'ResizeFromStream

    '''-----------------------------------------------------------------------------
    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="image"></param>
    ''' <param name="szFileName"></param>
    ''' <param name="lCompression"></param>
    ''' <remarks></remarks>
    ''' <history>
    ''' 	[wcwilson] 	6/9/2003	Created
    ''' </history>
    '''-----------------------------------------------------------------------------
    Private Sub SaveJPGWithCompressionSetting(ByVal image As System.Drawing.Image, _
        ByVal szFileName As String, ByVal lCompression As Long)
        Dim eps As EncoderParameters = New EncoderParameters(1)
        eps.Param(0) = New EncoderParameter(System.Drawing.Imaging.Encoder.Quality, lCompression)
        Dim ici As ImageCodecInfo = GetEncoderInfo("image/jpeg")
        image.Save(szFileName, ici, eps)
    End Sub

#End Region

#Region " Clean Strings "

    Public Shared Function Clean(ByVal strInput As String) As String
        If strInput Is Nothing Then
            Return String.Empty
        Else
            Return StripBadCharsDB(strInput).Replace("'s", "")
        End If
    End Function

    Public Shared Function CleanURLFileName(ByVal strInput As String) As String
        If strInput Is Nothing Then
            Return String.Empty
        Else
            Return StripBadCharsDB(strInput).Replace(" ", "_")
        End If
    End Function

    Public Shared Function StripBadChars(ByVal strIn As String) As String
        Return Regex.Replace(strIn, "(\s)|(,)|(;)|(:)|(')", "_")
    End Function

    Public Shared Function StripBadCharsDB(ByVal strIn As String) As String
        Return Regex.Replace(strIn, "(,)|(;)|(:)|(')", "_")
    End Function

#End Region

End Class